package com.zhenyi.xiaohuoche.admin;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.cjw.model.DBMap;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.utils.AESUtils;
import com.utils.AuthUtils;
import com.utils.DateUtils;
import com.utils.PathUtils;
import com.utils.interceptor.TestInterceptor;
import com.zhenyi.xhc.core.TicketUtils;
import com.zhenyi.xhc.core.XHCAuthInterceptor;
import com.zhenyi.xhc.core.XHCController;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

@Before(XHCAuthInterceptor.class)
public class AdminController extends XHCController {

	@Clear
	public void auth() {
		String account = getPara("account");
		String password = getPara("password");
		if (!StrKit.notBlank(account, password)) {
			renderFailure();
			return;
		}
		String token = "xhc" + DateUtil.now();
		String de = AESUtils.decrypt(AES_KEY, password);
		String acc = PropKit.get("acc", "admin");
		String pwd = PropKit.get("pwd", "admin");
		if (!acc.equals(account) || !pwd.equals(de)) {
			renderFailure();
			return;
		}
		token = DigestUtil.md5Hex(token);
		renderResult(AuthUtils.login(token, this));
		new Thread(new Runnable() {
			public void run() {
				ThreadUtil.safeSleep(60000);
				logout();
			}
		}).start();
	}

	public void logout() {
		AuthUtils.logout(this);
		renderSuccess();
	}

	@Override
	@Clear
	public void index() {
		render("/xhc/release/index.html");
	}

	/**
	 * 按照年月日下载进场统计
	 */
	public void downloadEnroll() {
		Date start = getStartDate();
		Date end = getEndDate();
		String type = "进场统计";
		String title = type + DateUtil.now();
		SqlPara sqlPara = Db.getSqlPara("Endroll", start, end);
		List<Record> pages = Db.find(sqlPara);
		String excelTitle = DateUtils.dateFormat(start, DateUtils.YYYYMMDD) + "至"
				+ DateUtils.dateFormat(end, DateUtils.YYYYMMDD) + type;
		ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();
		for (Record record : pages) {
			Map<String, Object> item = new LinkedHashMap<>();
			item.put("微信昵称", record.get("nickName"));
			item.put("进场时间", record.getDate("addTime"));
			item.put("票面时间", record.getDate("ticketTime"));
			rows.add(item);
		}

		String path = PathUtils.getFile("xhc", "download", title + ".xlsx");
		ExcelWriter writer = ExcelUtil.getWriter(path);
		writer.merge(2, excelTitle);
		// 一次性写出内容
		writer.write(rows);
		// 关闭writer，释放内存
		writer.close();
		File file = new File(path);
		renderFile(file);
	}

	/**
	 * 按照年月日至年月日下载所有订单 order
	 */
	public void downloadOrders() {
		Date start = getStartDate();
		Date end = getEndDate();
		String title = "所有订单" + DateUtil.now();
		SqlPara sqlPara = Db.getSqlPara("AdminOrders", start, end);
		List<Record> pages = Db.find(sqlPara);
		String excelTitle = DateUtils.dateFormat(start, DateUtils.YYYYMMDD) + "至"
				+ DateUtils.dateFormat(end, DateUtils.YYYYMMDD) + "所有订单";
		ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();
		for (Record record : pages) {
			int status = record.getInt("status");
			String statusString = "";
			if (status == 1) {
				statusString = "已支付";
			} else if (status == 0) {
				statusString = "未支付";
			} else if (status == -1) {
				statusString = "已退款";
			}
			String attach = record.get("attach");
			String attachString = "";
			if (attach.equals("ticket")) {
				attachString = "票";
			} else if (attach.equals("present")) {
				attachString = "礼品";
			}
			int paid = record.get("paid");
			int paidCount = paid / 100;
			Map<String, Object> item = new LinkedHashMap<>();
			item.put("订单号", record.get("out_trade_no"));
			item.put("支付时间", record.getDate("addTime"));
			item.put("价钱（元）", paidCount);
			item.put("订单类型", attachString);
			item.put("客户名称", record.get("nickName"));
			item.put("支付状态", statusString);
			rows.add(item);
		}

		String path = PathUtils.getFile("xhc", "download", title + ".xlsx");
		ExcelWriter writer = ExcelUtil.getWriter(path);
		writer.merge(5, excelTitle);
		// 一次性写出内容
		writer.write(rows);
		// 关闭writer，释放内存
		writer.close();
		File file = new File(path);
		renderFile(file);
	}

	/**
	 * 按照年月日至年月日下载所有票 usertickets
	 */
	public void downloadTickets() {
		Date start = getStartDate();
		Date end = getEndDate();
		String title = "票务订单" + DateUtil.now();
		SqlPara sqlPara = Db.getSqlPara("AdminUserTickets", start, end);
		List<Record> pages = Db.find(sqlPara);
		String excelTitle = DateUtils.dateFormat(start, DateUtils.YYYYMMDD) + "至"
				+ DateUtils.dateFormat(end, DateUtils.YYYYMMDD) + "票务订单";
		ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();
		for (Record record : pages) {
			int status = record.getInt("status");
			String statusString = "";
			if (status == 1) {
				statusString = "已支付";
			} else if (status == -1) {
				statusString = "已退款";
			}
			Map<String, Object> item = new LinkedHashMap<>();
			item.put("订单时间", record.getDate("addTime"));
			item.put("进场时间", record.getDate("time"));
			item.put("订单号", record.get("no"));
			item.put("微信昵称", record.get("nickname"));
			item.put("姓名", record.get("name"));
			item.put("电话", record.get("mobile"));
			item.put("支付金额", record.getBigDecimal("paid").toString());
			item.put("票务信息", record.get("title"));
			item.put("使用状态", record.getInt("isUsed") == null ? "" : "已使用");
			item.put("支付状态", statusString);
			rows.add(item);
		}

		String path = PathUtils.getFile("xhc", "download", title + ".xlsx");
		ExcelWriter writer = ExcelUtil.getWriter(path);
		writer.merge(9, excelTitle);
		// 一次性写出内容
		writer.write(rows);
		// 关闭writer，释放内存
		writer.close();
		File file = new File(path);
		renderFile(file);
	}

	/**
	 * 按照年月日至年月日下载所有小礼品 userPresents
	 */
	public void downloadPresents() {
		Date start = getStartDate();
		Date end = getEndDate();
		SqlPara sqlPara = Db.getSqlPara("AdminPresentsOrder", start, end);
		List<Record> pages = Db.find(sqlPara);

		String type = "小礼品订单";
		String title = type + DateUtil.now();
		String excelTitle = DateUtils.dateFormat(start, DateUtils.YYYYMMDD) + "至"
				+ DateUtils.dateFormat(end, DateUtils.YYYYMMDD) + type;
		ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();
		for (Record record : pages) {
			int status = record.getInt("status");
			String statusString = "";
			if (status == 1) {
				statusString = "已支付";
			} else if (status == -1) {
				statusString = "已退款";
			}
			Map<String, Object> item = new LinkedHashMap<>();
			item.put("订单时间", record.getDate("addTime"));
			item.put("订单号", record.get("presentNo"));
			item.put("微信昵称", record.get("nickname"));
			item.put("微信昵称", record.get("nickName"));
			item.put("姓名", record.get("userName"));
			item.put("电话", record.get("telNumber"));
			item.put("地址", record.get("address"));
			item.put("快递单号", record.get("trackNo"));
			item.put("支付金额(分)", record.getBigDecimal("total").toString());
			item.put("礼物信息", record.get("title"));
			item.put("支付状态", statusString);
			rows.add(item);
		}

		String path = PathUtils.getFile("xhc", "download", title + ".xlsx");
		ExcelWriter writer = ExcelUtil.getWriter(path);
		writer.merge(9, excelTitle);
		// 一次性写出内容
		writer.write(rows);
		// 关闭writer，释放内存
		writer.close();
		File file = new File(path);
		renderFile(file);
	}

	/**
	 * 列出全部微信用户(xhcwechat),昵称,性别,电话
	 */
	public void user() {
	}

	@Override
	public void info() {
		super.info();
		// String settingPath = PathUtils.getFile("xhc", "xhc.setting");
		// Setting setting = new Setting("xhc.setting");
		// int adultPrice = setting.getInt("adultPrice", "setting", 60);
		// setting.set("adultPrice", "setting", adultPrice + 1);
		// setting.store(path);
		String notice = new FileReader(PathUtils.getFile("xhc", "notice.txt")).readString();
		String agreement = new FileReader(PathUtils.getFile("xhc", "agreement.txt")).readString();
		String notification = new FileReader(PathUtils.getFile("xhc", "notification.txt")).readString();
		String openTime = new FileReader(PathUtils.getFile("xhc", "openTime.txt")).readString();
		String closeTime = new FileReader(PathUtils.getFile("xhc", "closeTime.txt")).readString();
		DBMap map = new DBMap();
		map.put("notice", notice);
		map.put("agreement", agreement);
		map.put("notification", notification);
		map.put("openTime", openTime);
		map.put("closeTime", closeTime);
		map.put("images", new FileReader(PathUtils.getFile("xhc", "images.txt")).readString());
		renderResult(map);
	}

	@Override
	public void update() {
		String notice = getPara("notice");
		if (StrKit.notBlank(notice)) {
			new FileWriter(PathUtils.getFile("xhc", "notice.txt")).write(notice);
		}
		String agreement = getPara("agreement");
		if (StrKit.notBlank(agreement)) {
			new FileWriter(PathUtils.getFile("xhc", "agreement.txt")).write(agreement);
		}
		String notification = getPara("notification");
		if (StrKit.notBlank(notification)) {
			new FileWriter(PathUtils.getFile("xhc", "notification.txt")).write(notification);
		}
		String images = getPara("images");
		if (StrKit.notBlank(images)) {
			new FileWriter(PathUtils.getFile("xhc", "images.txt")).write(images);
		}
		String openTime = getPara("openTime", "8:00");
		new FileWriter(PathUtils.getFile("xhc", "openTime.txt")).write(openTime);

		String closeTime = getPara("closeTime", "20:00");
		new FileWriter(PathUtils.getFile("xhc", "closeTime.txt")).write(closeTime);

		// rootSetting.set("openTime", "ticketSetting", openTime);
		// rootSetting.set("closeTime", "ticketSetting", closeTime);
		// rootSetting.store(settingPath);
		renderSuccess();
	}

	@Clear
	@Before(TestInterceptor.class)
	public void gen() {
		new TicketUtils().genTicket();
		renderSuccess();
	}
}
